package com.cn.jx.manager.controller;

import java.text.MessageFormat;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import com.jx.base.SessionUser;
import com.jx.jpaQuery.ConvertCondition;
import com.jx.jpaQuery.PageCondition;
import com.jx.jpaQuery.QueryCondition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.cn.jx.common.controller.BaseController;
import com.cn.jx.common.util.page.PageObj;
import com.cn.jx.manager.form.RoleForm;
import com.cn.jx.manager.po.Role;
import com.cn.jx.manager.service.mtn.IResourceServiceMtn;
import com.cn.jx.manager.service.mtn.IRoleServiceMtn;
import com.cn.jx.manager.service.query.IResourceServiceQry;
import com.cn.jx.manager.service.query.IRoleServiceQry;
import com.jx.enumType.DataGrideTypeEnum;
import com.jx.enumType.ResourceEnum;
import com.jx.exception.MyException;
import com.jx.model.MenuEntry;
import com.jx.util.FormValidat;
import com.jx.util.MapObject;
import com.jx.util.Response;
import com.jx.util.Utility;

/**
 * 
 * @author 姜旭
 * @version v1.11.20.2019
 * @since
 *        <p> 创建时间：2019年12月1日
 *        <p> 功能描述:角色控制层
 *        <p> 官方网站：management/admin/index
 *        <p>  邮箱地址：524577360@qq.com
 * @Description 角色控制层
 */
@Controller
@RequestMapping("/admin/permissions/role/")
public class RoleController extends BaseController {
	
	/**
	 * 定义{@link IResourceServiceQry IResourceServiceQry <tt>定义资源</tt>}
	 */
	@Autowired
	protected IResourceServiceQry resourceServiceQry;
	/**
	 * 定义{@link IResourceServiceMtn IResourceServiceMtn <tt>定义资源</tt>}
	 */
	@Autowired
	protected IResourceServiceMtn resourceServiceMtn;
	/**
	 * 定义{@link IRoleServiceQry IRoleServiceQry <tt>定义角色</tt>}
	 */
	@Autowired
	protected IRoleServiceQry roleServiceQry;
	/**
	 * 定义{@link IRoleServiceMtn IRoleServiceMtn <tt>定义角色</tt>}
	 */
	@Autowired
	protected IRoleServiceMtn roleServiceMtn;
	
	/**
	 * 定义静态路径
	 */
	private static final String _PAGE_PATH="roleresource/";
	
//============================================页面跳转开头====================================================================

	/**
	 * 
	 * @Title:List
	 * @Description:TODO(页面跳转)
	 * <p>邮箱地址: 524577360@qq.com
	 * @throws
	 */
	@RequestMapping("list/{path}")
	public String List(Model model, HttpServletRequest request,@PathVariable(value = "path") String path) {
		SessionUser sessUser = getSessionUser(request);
		// 设置表头
		setModelColumns(model, DataGrideTypeEnum.ROLE_MGR);
		setModelPermit(model,ResourceEnum.ROLE_MGR,sessUser.getResourceCodeList());
		return MessageFormat.format("{0}{1}", _PAGE_PATH,"recycle".equals(path)?"role/rolerecycle":"rolelist");
	}
	 
	 
	 /**
	  * 
	 * @Title:editWindow
	 * @Description:TODO(页面跳转到编辑更新页面)
	 * <p>邮箱地址: 524577360@qq.com
	 * @throws
	  */
	@RequestMapping("edit")
	public String editWindow(Model model, HttpServletRequest request, String id) {
		// id存在 则为修改编辑
		// 角色信息
		Role res = null;
		if (Utility.isNotBlank(id)) {
			res = roleServiceQry.getRoleById(id);
		}
		model.addAttribute("res", res);
		return _PAGE_PATH + "role/roleedit";
	}
	 

	 /**
	  * 
	 * @Title:allotResourceWindow
	 * @Description:TODO(跳转到角色分配页面)
	 * <p>邮箱地址: 524577360@qq.com
	  */
	@RequestMapping("allotResource")
	public String allotResourceWindow(Model model, String id) {
		// 获取已经分配的资源
		model.addAttribute("roleId", id);
		return _PAGE_PATH + "role/roleallotres";
	}
	 
//============================================页面跳转结束====================================================================

//============================================角色请求开头====================================================================
	/**
	* @Title:roleList
	* @Description:TODO(分页查询角色)
	* <p>邮箱地址: 524577360@qq.com
	* @throws
	 */
	@RequestMapping("listData/{path}")
	@ResponseBody
	public PageObj<MapObject> roleList(Model model, @PathVariable(value = "path") String path, PageCondition page) {
		QueryCondition cond = ConvertCondition.initCondition(page, path);
		try {
			PageObj<MapObject> pageuser = roleServiceQry.findRoleByPageAndParams(cond);
			return pageuser;
		} catch (Exception e) {
			e.printStackTrace();
			log.debug(e.getMessage());
		}
		return null;
	}
	
	
	/**
	 * 
	* @Title:addRole
	* @Description:TODO(保存或更新角色)
	* <p>邮箱地址: 524577360@qq.com
	* @throws
	 */
	@RequestMapping("addOrUpdate")
	@ResponseBody
	public Response addRole(Model model, HttpServletRequest request, RoleForm role) {
		SessionUser sessUser = getSessionUser(request);
		// 表单验证
		try {
			FormValidat.exec(role);
			role.setOperatUser(sessUser.getUserId());
			roleServiceMtn.saveOrUpdateRole(role);
			return Response.Success();
		} catch (MyException e) {
			e.printStackTrace();
			log.debug(e.getMessage());
			return Response.Fail(e.getMessage());
		}
	}
	
	/**
	 * 
	* @Title:delRole
	* @Description:TODO(删除角色 标记删除)
	* <p>邮箱地址: 524577360@qq.com
	* @throws
	 */
	@RequestMapping("delete")
	@ResponseBody
	public Response delRole(Model model, HttpServletRequest request, String ids) {
		SessionUser sessUser = getSessionUser(request);
		try {
			// 表单验证
			FormValidat.validId(ids);
			// 表单验证
			List<String> list = JSON.parseArray(ids, String.class);
			roleServiceMtn.delRole(list, sessUser.getUserId());
			return Response.Success();
		}catch (Exception e) {
			log.debug(e.getMessage());
			return Response.Fail(e.getMessage());
		}
	}
	
	/**
	 * 
	* @Title:removeRole
	* @Description:TODO(移除角色 清空回收站)
	* <p>邮箱地址: 524577360@qq.com
	* @throws
	 */
	@RequestMapping("remove")
	@ResponseBody
	public Response removeRole(Model model, HttpServletRequest request, String ids) {
		SessionUser sessUser = getSessionUser(request);
		try {
			// 表单验证
			FormValidat.validId(ids);
			// 表单验证
			List<String> list = JSON.parseArray(ids, String.class);
			roleServiceMtn.removeRole(list, sessUser.getUserId());
			return Response.Success();
		} catch (Exception e) {
			log.debug(e.getMessage());
			return Response.Fail(e.getMessage());
		}
	}
	
	/**
	 * 
	* @Title:removeRole
	* @Description:TODO(找回)
	* <p>邮箱地址: 524577360@qq.com
	* @throws
	 */
	@RequestMapping("recover")
	@ResponseBody
	public Response recoverRole(Model model, HttpServletRequest request, String ids) {
		SessionUser sessUser = getSessionUser(request);
		try {
			// 表单验证
			FormValidat.validId(ids);
			// 表单验证
			List<String> list = JSON.parseArray(ids, String.class);
			roleServiceMtn.recoverRole(list, sessUser.getUserId());
			return Response.Success();
		} catch (Exception e) {
			log.debug(e.getMessage());
			return Response.Fail(e.getMessage());
		}
	}
	
	/**
	 * 
	* @Title:removeRole
	* @Description:TODO(移除角色 清空回收站)
	* <p>邮箱地址: 524577360@qq.com
	* @throws
	 */
	@RequestMapping("removeAll")
	@ResponseBody
	public Response removeAllRole(Model model, HttpServletRequest request) {
		SessionUser sessUser = getSessionUser(request);
		try {
			roleServiceMtn.removeRoleAll(sessUser.getUserId());
			return Response.Success();
		} catch (Exception e) {
			log.debug(e.getMessage());
			return Response.Fail(e.getMessage());
		}
	}
	
	 /**
	  * 
	 * @Title:getRoleById
	 * @Description:TODO(查询角色对象)
	 * <p>邮箱地址: 524577360@qq.com
	 * @throws
	  */
	 @RequestMapping("get")
	 @ResponseBody
	 public Response getRoleById(Model model,String id) {
		 Role uf= roleServiceQry.getRoleById(id);
		 return Response.Success(uf);
	 }
	 
	 /**
	  * 
	 * @Title:roleResourceRelation
	 * @Description:TODO(角色分配权限)
	 * <p>邮箱地址: 524577360@qq.com
	 * @throws
	  */
	@RequestMapping("resource/relation")
	@ResponseBody
	public Response roleResourceRelation(Model model, HttpServletRequest request, String roleId) {
		SessionUser sessUser = getSessionUser(request);
		try {
			// 获取所有配置的资源
			String[] resourceId = request.getParameterValues("resourceId[]");
			// 分派资源
			roleServiceMtn.addRoleResource(roleId, resourceId, sessUser.getUserId());
			return Response.Success();
		} catch (Exception e) {
			log.debug(e.getMessage());
			return Response.Fail(e.getMessage());
		}
	}
	 
	 /**
	  * 
	 * @Title:roleresourceTree
	 * @Description:TODO(分配角色控件树形菜单)
	 * <p>邮箱地址: 524577360@qq.com
	 * @throws
	  */
	@RequestMapping("resource/listTree")
	@ResponseBody
	public List<MenuEntry> roleresourceTree(Model model, String parent, String roleId) {
		try {
			Set<String> selected = roleServiceQry.findAllResourceByRole(roleId);// 获取这个角色选中的资源
			// 根据父编码循环获取子资源 孙子资源 树形结构。并且角色有的被勾选
			List<MenuEntry> result = resourceServiceQry.findResourceRoleTree(parent, selected);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			log.debug(e.getMessage());
		}
		return null;
	}
	
}
